package br.gendi.dialog;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;

import au.id.jericho.lib.html.Source;
import au.id.jericho.lib.html.Tag;
import br.gendi.core.Parser;

public class Visualizador {

	private Shell sShell = null;
	private TabFolder tabFolder = null;
	private Composite c = null;
	private Color white = null;
	private Color black = null;

	public Visualizador() {
		super();
		createSShell();
		//sShell.open();
	}

	private void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.verticalSpacing = 2;
		sShell = new Shell();		   
		sShell.setText("Resultados");
		createTabFolder();
		sShell.setLayout(gridLayout);
		sShell.setSize(new Point(800,600));
		InputStream isLarge = getClass().getClassLoader().getResourceAsStream("icons\\mainicon32.png");
		InputStream isSmall = getClass().getClassLoader().getResourceAsStream("icons\\mainicon16.png");

		Image large = new Image(sShell.getDisplay(), isLarge);
		Image small = new Image(sShell.getDisplay(), isSmall);

		sShell.setImages(new Image[] {small, large});
		white = sShell.getDisplay().getSystemColor(SWT.COLOR_WHITE);
		black = sShell.getDisplay().getSystemColor(SWT.COLOR_BLACK);

	}

	private void createTabFolder() {
		GridData gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.verticalAlignment = GridData.FILL;
		gridData.grabExcessVerticalSpace = true;
		tabFolder = new TabFolder(sShell, SWT.NONE);
		tabFolder.setLayoutData(gridData);
		c = new Composite(new Shell(),SWT.NONE);
		c.setVisible(false);

	}


	private boolean done = false;

	public void adicionarSite(final String nome, String url) {
		final Browser b = new Browser(c, SWT.NONE);
		b.setUrl(url);
		b.setVisible(false);



		b.addStatusTextListener(new StatusTextListener() {
			public void changed(StatusTextEvent arg0) {
				if (arg0.text.equalsIgnoreCase("Concluído") || arg0.text.equalsIgnoreCase("done")) {
					if (done == false) {
						String texto = ((Browser)arg0.widget).getText();
						done = true;
						salvarEmHTML(texto, nome+".html");
						Source source = null;
						try {
							source=new Source(new FileReader(new File(nome+".html")));
						} catch (Exception e) {
							e.printStackTrace();
						}

						List l = source.findAllElements(Tag.IMG);
						String html = source.toString();
						for (int i=0;i<l.size(); i++) 
							html = html.replaceAll(l.get(i).toString(), "");
						b.setText(html);

						TabItem tabItem1 = new TabItem(tabFolder, SWT.NONE);
						Text lista = new Text(tabFolder, SWT.MULTI | SWT.H_SCROLL  | SWT.READ_ONLY |  SWT.V_SCROLL);
						lista.setBackground(white);
						lista.setForeground(black);
						lista.setFont(new Font(Display.getDefault(), "Courier New", 10, SWT.NORMAL));
						lista.setText(html);
						tabItem1.setControl(lista);
						tabItem1.setText(nome);
					}
					if (!sShell.isVisible())
						sShell.open();
				}
			}
		});

	}

	public void adicionarSiteHTML(String nome, String html) {
		Text lista = new Text(tabFolder, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY);
		lista.setBackground(white);
		lista.setForeground(black);
		lista.setFont(new Font(Display.getDefault(), "Courier New", 10, SWT.NORMAL));
		salvarEmHTML(html, nome+".html");

		Source source = null;
		try {
			source=new Source(new FileReader(new File(nome+".html")));
		} catch (Exception e) {
			e.printStackTrace();
		}

		List l = source.findAllElements(Tag.IMG);
		String html2 = source.toString();
		for (int i=0;i<l.size(); i++) 
			html2 = html2.replaceAll(l.get(i).toString(), "");

		lista.setText(html2);

		TabItem tabItem1 = new TabItem(tabFolder, SWT.NONE);
		tabItem1.setControl(lista);
		tabItem1.setText(nome);
	}


	private void salvarEmHTML(String texto, String fileName) {

		try
		{
			FileWriter fileWriter = new FileWriter( fileName );
			BufferedWriter bufferedWriter = new BufferedWriter( fileWriter );
			bufferedWriter.write(texto);
			bufferedWriter.close();

			String retornoSemCSS;
			retornoSemCSS = Parser.removerCSS(fileName);
			retornoSemCSS = Parser.removerStyle(fileName);
			retornoSemCSS = Parser.removerHTML(fileName);

			fileWriter = new FileWriter( fileName );
			bufferedWriter = new BufferedWriter( fileWriter );
			bufferedWriter.write(retornoSemCSS);
			bufferedWriter.close();
		}
		catch( IOException e )
		{
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void adicionar(String nome, final String html) {
		Browser b = new Browser(tabFolder, SWT.NONE);
		b.setText(html);
		TabItem tabItem1 = new TabItem(tabFolder, SWT.NONE);
		tabItem1.setControl(b);
		tabItem1.setText(nome);

		if (!sShell.isVisible())
			sShell.open();
		
//		AdvancedStatusTextListener a = new AdvancedStatusTextListener(nome);
//		b.addStatusTextListener(a);
//		
//		boolean terminou = false;
//		
//		while (terminou != true) {
//			if (resultado.get(nome).equals(b.getText()))
//				terminou = false;
//			else
//				terminou = true;
//		}
//		b.setText(resultado.get(nome));
	}
	
	private HashMap<String, String> resultado = new HashMap<String, String>();

	class AdvancedStatusTextListener implements StatusTextListener {
		String nome="";
		public AdvancedStatusTextListener(String n) {
			nome = n;
		}
		public void changed(StatusTextEvent event) {
			System.out.println(event.text);
			String valor = ((Browser)event.widget).getText();
			System.out.println(valor);
			resultado.put(nome, valor);
			resultado.get(nome);
		}
	}
}
